﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using System.Transactions;
using Telerik.Web.UI;
using MediaMonitor.Common;

namespace MediaMonitor.Admin
{
    public partial class User_Mgmt_AddEdit : Adex.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);

                //fill companies list
                FillCompanies();

                string uid = Utility.GetRequestedVal("uid", "0");
                string cid = Utility.GetRequestedVal("cid", "0");

                if (cid != "0")
                {
                    hdnCurCId.Value = cid;
                    Utility.SelectListItem(lstCompany, cid);
                }

                if (uid == "0")
                {
                    hdnFormMode.Value = "add";
                    hdnCurPkId.Value = uid;
                }
                else
                {
                    hdnFormMode.Value = "edit";
                    hdnCurPkId.Value = uid;
                    DoEdit();
                }

            }

            lblMsg.Text = lblMsg_top.Text = "";
            SetCrudButtons();

        }

        private void FillCompanies()
        {

            lstCompany.DataSourceID = "sqlDSComp";
            lstCompany.DataBind();

            lstCompany.Items.Insert(0, new ListItem("- Select a Company -", "0"));

        }


        protected void DoEdit()
        {


            VSiteUser usr = new VSiteUser("SiteUserID", hdnCurPkId.Value);

            //this.lstCompany.SelectedValue = comp.CompanyName;

            Utility.SelectListItem(lstCompany, usr.CompanyCode.ToString());

            this.tbValidFrom.Text = Utility.ToDateTime(usr.ValidFrom).ToString("MM/dd/yyyy");
            this.tbValidTo.Text = Utility.ToDateTime(usr.ValidTo).ToString("MM/dd/yyyy");



            this.chkAcitve.Checked = usr.Active;


            //get the user account 

            if (usr.SiteUserID > 0)
            {
                tbFullName.Text = usr.FullName;
                tbLoginName.Text = usr.UserName;
                tbLoginName.Enabled = false; // username can't be changed
                tbPassword.Text = usr.Password;
                tbEmail.Text = usr.Email;
                tbCell.Text = usr.Cell;
            }

            pnlForm.Focus();


        }

        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            if (!IsValid) { return; }

            if (hdnFormMode.Value == "add" && hdnCurPkId.Value == "0")
            {
                //company selection check
                if (lstCompany.SelectedItem == null)
                {
                    lblMsg.Text = lblMsg_top.Text = "You need to select a valid Company from drop down list";
                    return;
                }

                //check company validity date
                Company comp = new Company(lstCompany.SelectedValue);
                DateTime validFrom = Utility.ToDateTime(tbValidFrom.Text);
                DateTime validTo = Utility.ToDateTime(tbValidTo.Text);
                if (validFrom < comp.ValidFrom || validTo > comp.ValidTo)
                {
                    lblMsg.Text = lblMsg_top.Text = "You need to select the 'Valid to' and 'Valid from' dates within the validity period of their parent company which is from " + comp.ValidFrom.Value.ToShortDateString() + " to" + comp.ValidTo.Value.ToShortDateString();
                    return;
                }

                //save user details
                string errMsg = "";

                int uid = AppUser.AddSiteUser(tbLoginName.Text.Trim(), tbPassword.Text.Trim(), "user", tbEmail.Text.Trim(), Utility.ToInt(lstCompany.SelectedValue), chkAcitve.Checked, out errMsg);


                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromMinutes(10)))
                {
                    using (SubSonic.SharedDbConnectionScope conn = new SubSonic.SharedDbConnectionScope(System.Configuration.ConfigurationManager.ConnectionStrings["DBAdex"].ToString()))
                    {

                        try
                        {


                            if (uid <= 0)
                            {
                                throw new Exception(errMsg);
                            }

                            //update rest of the details.

                            SiteUser usr = new SiteUser(uid);
                            usr.FullName = tbFullName.Text;
                            usr.CompanyCode = Utility.ToInt(this.lstCompany.SelectedValue);
                            usr.ValidFrom = Utility.ToDateTime(tbValidFrom.Text);
                            usr.ValidTo = Utility.ToDateTime(tbValidTo.Text);
                            usr.Cell = tbCell.Text;
                            usr.Active = chkAcitve.Checked;

                            ////activate the user associated with this company account.
                            //if (!AppUser.SetSiteUserActivation(usr, usr.Active))
                            //    throw new Exception("Error setting SiteUser Activation settings");

                            usr.DateAdded = DateTime.Now;
                            usr.DateModified = DateTime.Now;

                            usr.Save();

                            ts.Complete();
                            lblMsg.Text = lblMsg_top.Text = "User added successfully";

                        }//end first try
                        catch (Exception ex)
                        {
                            conn.Dispose();
                            ts.Dispose();
                            lblMsg.Text = lblMsg_top.Text = "Failed to save this User: error--> " + ex.Message;
                            return;
                        }
                    }//end conn
                }//end ts



                hdnFormMode.Value = "add";
                hdnCurPkId.Value = "0";
                Utility.ClearForm(pnlForm);
                SetCrudButtons();

                pnlIno.Visible = true;
                pnlForm.Visible = false;
            }
        }

        protected void btnUpdate_Click(object sender, ImageClickEventArgs e)
        {

            if (!IsValid) { return; }


            if (hdnFormMode.Value == "edit" && hdnCurPkId.Value != "0")
            {


                string errMsg = "";

                //company selection check.
                if (lstCompany.SelectedItem == null)
                {
                    lblMsg.Text = lblMsg_top.Text = "You need to select a valid Company from drop down list";
                    return;
                }

                //check company validity date
                Company comp = new Company(lstCompany.SelectedValue);
                DateTime validFrom = Utility.ToDateTime(tbValidFrom.Text);
                DateTime validTo = Utility.ToDateTime(tbValidTo.Text);
                if (validFrom < comp.ValidFrom || validTo > comp.ValidTo)
                {
                    lblMsg.Text = lblMsg_top.Text = "You need to select the 'Valid to' and 'Valid from' dates within the validity period of their parent company which is from " + comp.ValidFrom.Value.ToShortDateString() + " to" + comp.ValidTo.Value.ToShortDateString();
                    return;
                }

                SiteUser usr = new SiteUser(hdnCurPkId.Value);

                //set User login details 
                if (AppUser.UpdateUser(usr.SiteUserID, tbLoginName.Text.Trim(), tbPassword.Text.Trim(), out errMsg) == false)
                {
                    lblMsg.Text = lblMsg_top.Text = "Failed to update this User. " + errMsg;
                    return;
                }

                //activate the user associated with this company account.
                if (!AppUser.SetSiteUserActivation(usr, chkAcitve.Checked))
                    lblMsg.Text = lblMsg_top.Text = "Error setting SiteUser Activation settings";



                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(10)))
                {
                    using (SubSonic.SharedDbConnectionScope conn = new SubSonic.SharedDbConnectionScope(System.Configuration.ConfigurationManager.ConnectionStrings["DBAdex"].ToString()))
                    {

                        try
                        {


                            usr.Email = tbEmail.Text;

                            usr.CompanyCode = Utility.ToInt(this.lstCompany.SelectedValue);

                            usr.FullName = tbFullName.Text;
                            usr.ValidFrom = Utility.ToDateTime(tbValidFrom.Text);
                            usr.ValidTo = Utility.ToDateTime(tbValidTo.Text);
                            usr.Cell = tbCell.Text;
                            usr.Active = chkAcitve.Checked;


                            usr.DateModified = DateTime.Now;

                            usr.Save();


                            ts.Complete();
                            lblMsg.Text = lblMsg_top.Text = "User updated successfully";

                        }//end first try
                        catch (Exception ex)
                        {
                            lblMsg.Text = lblMsg_top.Text = "Failed to update this User: error --> " + ex.Message;
                            return;
                        }

                    }//end conn
                }//end ts

                hdnCurPkId.Value = "0";
                hdnFormMode.Value = "add";

                Utility.ClearForm(pnlForm);

                SetCrudButtons();

                pnlIno.Visible = true;
                pnlForm.Visible = false;

            }
        }

        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (hdnCurPkId.Value.Length > 0 && hdnFormMode.Value == "edit")
            {
                try
                {
                    SiteUser usr = new SiteUser(hdnCurPkId.Value);
                    AppUser.DeleteSiteUser(usr);
                    SiteUser.Delete(hdnCurPkId.Value);
                    lblMsg.Text = lblMsg_top.Text = "Selected User deleted successfully";
                }
                catch (Exception ex)
                {
                    lblMsg.Text = lblMsg_top.Text = "Selected User cannot be deleted. [" + ex.Message + "]";
                }

                hdnFormMode.Value = "add";
                hdnCurPkId.Value = "0";
                Utility.ClearForm(pnlForm);
                SetCrudButtons();

                pnlIno.Visible = true;
                pnlForm.Visible = false;
            }
        }

        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {

            hdnCurPkId.Value = "0";
            hdnFormMode.Value = "add";
            Utility.ClearForm(pnlForm);

            SetCrudButtons();

            pnlIno.Visible = true;
            pnlForm.Visible = false;

        }

        private void SetCrudButtons()
        {
            btnCancel.Visible = btnDelete.Visible = btnUpdate.Visible = btnCancel_top.Visible = btnDelete_top.Visible = btnUpdate_top.Visible = hdnFormMode.Value == "edit";
            btnAdd.Visible = btnAdd_top.Visible = hdnFormMode.Value == "add";
        }


        protected void lstCompany_SelectedIndexChanged(object o, EventArgs e)
        {
            if (lstCompany.SelectedValue == "0") { return; }
            Company comp = new Company(lstCompany.SelectedValue);
            tbValidFrom.Text = comp.ValidFrom.Value.ToShortDateString();
            tbValidTo.Text = comp.ValidTo.Value.ToShortDateString();

        }
    }//end class
}